<template >
  <div style="height: 100%; display: flex; flex-direction: column">
    <CCard style="margin-bottom: 0; flex: 1">
      <CCardBody>
        <div class="titleText" style="margin-bottom: 10px">
          集群资源使用情况监控
        </div>
        <div class="dashboardContainer">
          <div class="echarts">
            <!-- 内存使用情况 -->
            <div id="main1" class="echartsImg firstecharts"></div>
            <div class="creation">
              <div class="title">内存使用情况</div>
              <div class="contentFirst content">
                已使用：{{ useMe }}GB 空闲：{{ kongMer }}GB
              </div>
            </div>
          </div>
          <div class="echarts" style="margin: 0 20px">
            <!-- CPU使用情况 -->
            <div id="main2" class="echartsImg"></div>
            <div class="creation">
              <div class="title">CPU使用情况</div>
              <div class="contentFirst content">
                总核数：{{ allCpu }} 空闲核数：{{ kongCpu }}
              </div>
            </div>
          </div>
          <!-- 存储使用情况 -->
          <div class="echarts">
            <div id="main3" class="echartsImg"></div>
            <div class="creation">
              <div class="title">存储使用情况</div>
              <div class="contentThree content">
                已使用：{{ useValue }}GB 空闲：{{ kongDisk }}GB
              </div>
            </div>
          </div>
        </div>
      </CCardBody>
    </CCard>
    <div style="display: flex; margin: 10px 0; flex: 1">
      <CCard style="margin-bottom: 0; margin-right: 10px; width: 50%">
        <CCardBody>
          <div class="titleText">数据下载速率</div>
          <div
            id="lineChart2"
            class="lineChart"
            style="padding: 0; margin: 0"
          ></div>
        </CCardBody>
      </CCard>
      <CCard style="margin-bottom: 0; width: 50%">
        <CCardBody>
          <div class="titleText">数据上传速率</div>
          <div id="lineChart3" class="lineChart" style></div>
        </CCardBody>
      </CCard>
    </div>
    <CCard style="flex: 1; max-height: 295px">
      <CCardBody>
        <div class="titleText" style="margin-bottom: 10px">
          节点负载情况监控
        </div>
        <div class="serverStyle">
          <div
            v-for="(item, index) in itemList"
            :key="index"
            class="serverDiv"
            @click="getInfo(item)"
          >
            <img
              src="@/assets/icons/server.svg"
              class="imgSize"
              alt
              v-show="green"
            />
            <img
              src="@/assets/icons/serve.svg"
              class="imgSize"
              alt
              v-show="yellow"
            />
            <div>{{ item.ip }}</div>
            <!-- <div class="nodeNameContent" @click="getInfo">{{item.name}}</div> -->
            <div id="nodes" class="nodeNameContent">{{ item.name }}</div>
          </div>
        </div>
      </CCardBody>
    </CCard>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "monitor",
  data() {
    return {
      download: {
        tData: [],
        vData: [],
      },
      downloadTdata: [],
      downloadVData: [],
      charts: "",
      allMer: 0,
      kongMer: 0,
      allCpu: 0,
      kongCpu: 0,

      allDisk: "",
      kongDisk: "",
      cpuValue: "",
      num: 1024.0,
      statusValue: 0,
      changeValue: 0,
      useMe: 0,
      optionsMe: {
        tooltip: {
          formatter: "{a} <br/>{c} {b}",
        },
        title: {
          text: "",
          left: "center",
          top: 0,
        },
        series: [
          {
            name: "内存",
            type: "gauge",
            detail: { formatter: "{value}%" },
            data: [{ value: 50, name: "使用率" }],
            axisLine: {
              //坐标轴线
              // 设置仪表盘颜色范围
              lineStyle: {
                // 属性lineStyle控制线条样式
                width: 10, // 半径（环的宽度）
                color: [[1.1, "#ff5733"]],
              },
            },
            // 刻度分割线样式
            splitLine: {
              length: 12,
              lineStyle: {
                color: "white",
              },
            },
            detail: {
              //说明数字大小
              formatter: "{value}%",
              offsetCenter: ["0%", "60%"], //相对于仪表盘中心的偏移位置
              fontSize: 14,
              width: 100,
              color: "#000",
              // padding: [5, 15, 2, 15]
            },
          },
        ],
      },
      optionsCpu: {
        tooltip: {
          formatter: "{a} <br/>{c} {b}",
        },
        title: {
          text: "",
          left: "center",
          top: 0,
        },
        max: 100,
        series: [
          {
            name: "CPU",
            type: "gauge",
            max: 100,
            detail: { formatter: "{value}%" },
            data: [{ value: 50, name: "使用率" }],
            // center:["50%","45%"],
            // data: [
            //   {
            //     value: 50,
            //     name: "使用率"
            //   }
            // ],
            axisLine: {
              //坐标轴线
              // 设置仪表盘颜色范围
              lineStyle: {
                // 属性lineStyle控制线条样式
                width: 10, // 半径（环的宽度）
                color: [[1.1, "#499df8"]],
              },
            },
            // 刻度分割线样式
            splitLine: {
              length: 12,
              lineStyle: {
                color: "white",
              },
            },
            detail: {
              //说明数字大小
              formatter: "{value}%",
              offsetCenter: ["0%", "60%"], //相对于仪表盘中心的偏移位置
              fontSize: 14,
              width: 100,
              color: "#000",
              padding: [5, 15, 2, 15],
            },
          },
        ],
      },
      optionsDisk: {
        tooltip: {
          formatter: "{a} <br/>{c} {b}",
        },
        title: {
          text: "",
          left: "center",
          top: 0,
        },
        series: [
          {
            name: "存储",
            type: "gauge",
            detail: { formatter: "{value}%" },
            data: [{ value: 50, name: "使用率" }],
            axisLine: {
              //坐标轴线
              // 设置仪表盘颜色范围
              lineStyle: {
                // 属性lineStyle控制线条样式
                width: 10, // 半径（环的宽度）
                color: [[1.1, "#43cf7c"]],
              },
            },
            // 刻度分割线样式
            splitLine: {
              length: 12,
              lineStyle: {
                color: "white",
              },
            },
            detail: {
              //说明数字大小
              formatter: "{value}%",
              offsetCenter: ["0%", "60%"], //相对于仪表盘中心的偏移位置
              fontSize: 14,
              width: 100,
              color: "#000",
              // padding: [5, 15, 2, 15]
            },
          },
        ],
      },
      optionsDownload: {
        // title: {
        //   left: "left",
        //   text: "数据下载速率",
        // },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
          // data: this.downloadTData
        },
        yAxis: {
          name: "MB",
          type: "value",
        },
        series: [
          {
            // data: [820, 932, 901, 934, 1290, 1330, 1320,],
            data: [],
            type: "line",
          },
        ],
      },
      useValue: 0,
      optionsUpload: {
        // title: {
        //   left: "left",
        //   text: "数据上传速率"
        // },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          name: "",
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
          // data: this.downloadTData
        },
        yAxis: {
          name: "MB",
          type: "value",
        },
        series: [
          {
            // data: [820, 932, 901, 934, 1290, 1330, 1320,],
            data: [],
            type: "line",
          },
        ],
      },
      item: {
        ip: " ",
        name: " ",
      },
      itemList: [],
      green: false,
      yellow: false,
      timer: null,
    };
  },
  mounted() {
    if (this.$route.query.from === "adminHome") {
      // 调用父组件的方法
      this.$parent.$parent.headershowMonitor();
    }
    this.nowDate = this.$moment().format("YYYY年MM月DD日");
    let time = this.$moment(new Date()).valueOf() / 1000;
    //
    this.getKongMemory(); //集群空内存    ----内存使用情况：空闲
    this.getAllMemory(); //总内存         ----内存使用情况：已使用
    this.getDisk(); //磁盘总量            ----存储使用情况：已使用
    this.getDiskKong(); //磁盘空          ----存储使用情况：空闲
    this.getCpu(); //                    ----CPU使用情况

    this.getAllName(); //所有节点名称
    this.getLoad(); //节点负载
    let tmp = parseInt(Date.parse(new Date()).toString().substr(0, 10));
    let start = tmp - 24600;
    let end = tmp - 1000;
    let step = 36;
    this.getDownLoad(start, end, step);
    this.getTransmit(start, end, step);
    this.timer2 = setTimeout(() => {
      this.getAllMemory();
      this.getKongMemory();
      this.getDisk();
      this.getDiskKong();
      this.getCpu();
    }, 500);
    // 设置定时刷新
    this.timer = setInterval(() => {
      this.getAllMemory();
      this.getKongMemory();
      this.getDisk();
      this.getDiskKong();
      this.getCpu();


      // 生成当前时间时间戳  1h==3600
      let tmp = Date.parse(new Date()).toString();
      // 时间字符串截取
      tmp = tmp.substr(0, 10);
      // 时间字符串转数字
      let tmp2 = parseInt(tmp);
      let start = tmp2 - 24600;
      let end = tmp2 - 1000;
      let step = 36;
      this.getDownLoad(start, end, step);
      this.getTransmit(start, end, step);
    }, 10000);
    // this.timer2=setInterval(()=>{

    // },5000)
  },
  // 组件destroy前,清除定时器
  beforeDestroy() {
    clearInterval(this.timer);
    clearInterval(this.timer2);
  },
  watch: {
    statusValue(newVal, oldVal) {
      if (this.statusValue == 2) {
        // let _that = this;
        let columnar = this.$echarts.init(document.getElementById("main1"));
        this.useMe = (this.allMer - this.kongMer).toFixed(2);
        let usePart = (parseFloat(this.useMe) / parseFloat(this.allMer)) * 100;
        var s = usePart + "";
        var str = s.substring(0, s.indexOf(".") + 3);
        this.optionsMe.series[0].data[0].value = str;

        columnar.setOption(this.optionsMe);
      }
    },
    changeValue(newVal, oldVal) {
      if (this.changeValue == 2) {
        let _self = this;
        let columnar = _self.$echarts.init(document.getElementById("main3"));
        _self.useValue = (_self.allDisk - _self.kongDisk).toFixed(2);
        let usePart =
          (parseFloat(_self.useValue) / parseFloat(_self.allDisk)) * 100;
        var s = usePart + "";
        var str = s.substring(0, s.indexOf(".") + 3);
        _self.optionsDisk.series[0].data[0].value = str;

        columnar.setOption(_self.optionsDisk);
      }
    },
  },
  methods: {
    getInfo(data) {
      /*let nodeName = document.getElementById("nodes");
      let userLink = `/monitor/resourceNode/nodeDetails/${nodeName.innerHTML}`;
      // let userLink = `/monitor/resourceNode/nodeDetails/${nodeName}`;
      this.$router.push({ path: userLink });*/
      // this.$router.push({ name: "nodeDetails", params: { ip: data.ip } });

      this.$router.push({ name: "nodeDetails", params: { name: data.name } });
    },

    // 1.查询所有的节点名称
    getAllName() {
      let path = this.$api.monitorApi.getInfo;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          let nameData = res.data.data.nameList;
          let newData = [];
          for (var i = 0; i < nameData.length; i++) {
            let tempData = {};
            tempData.ip = nameData[i].ip_address;
            tempData.name = nameData[i].node_name;
            if (nameData[i].loadValue >= 0.99) {
              this.yellow = true;
              this.green = false;
            } else {
              this.green = true;
              this.yellow = false;
            }
            newData.push(tempData);
          }
          this.itemList = newData;
        } else {
        }
      });
    },
    // 2.查询集群CPU使用率
    getCpu() {
      let self = this;
      let columnar = this.$echarts.init(document.getElementById("main2"));
      let path = this.$api.monitorApi.getCpuInfo;
      axios.get(path).then((res) => {
        // freeCpu: 177  totalCpu: 224  use: "20.98%"
        let str = parseFloat(res.data.data.use);
        self.optionsCpu.series[0].data[0].value = str;
        self.allCpu = res.data.data.totalCpu;
        self.kongCpu = res.data.data.freeCpu;
        columnar.setOption(this.optionsCpu);
      });
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      // axios
      //   .get(path, {
      //     params: {
      //       query: "sum(rate(node_cpu_seconds_total[5m]))"
      //     }
      //   })
      //   .then(res => {
      //     console.log("getCpu",res)
      //     if (res.data.status) {
      //       let cpu = res.data.data.result;
      //       for (let i = 0; i < cpu.length; i++) {
      //         let newcpu = cpu[i].value[1];
      //         // let dattt = newcpu.toFixed(2)
      //         var s = newcpu + "";
      //         var str = s.substring(0, s.indexOf(".") + 3);
      //         console.log("strrrrr",str)
      //         self.optionsCpu.series[0].data[0].value = str;
      //         // console.log("cpu", self.optionsCpu.series[0].data[0].value);
      //       }
      //     } else {
      //     }
      //     columnar.setOption(this.optionsCpu);
      //   });
    },
    // 3.查询集群总内存
    getAllMemory() {
      let self = this;
      let path = this.$api.monitorApi.query1;
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      axios
        .get(path, {
          params: {
            query: "(sum(sum by (instance) (node_memory_MemTotal_bytes)))",
          },
        })
        .then((res) => {
          if (res.data.status) {
            let allMemory = res.data.data.result;
            for (let i = 0; i < allMemory.length; i++) {
              let allValue = allMemory[i].value;
              self.allMer = (
                allValue[1] /
                self.num /
                self.num /
                self.num
              ).toFixed(2);
              self.statusValue += 1;
            }
          } else {
          }
        });
    },
    // 4.查询集群内存空闲
    getKongMemory() {
      let self = this;
      let path = this.$api.monitorApi.query1;
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      axios
        .get(path, {
          params: {
            query: "(sum(sum by (instance) (node_memory_MemAvailable_bytes)))",
          },
        })
        .then((res) => {
          if (res.data.status) {
            let kongMemory = res.data.data.result;
            for (let i = 0; i < kongMemory.length; i++) {
              let kongValue = kongMemory[i].value;

              self.kongMer = (
                kongValue[1] /
                self.num /
                self.num /
                self.num
              ).toFixed(2);
              self.statusValue += 1;
            }
          } else {
          }
        });
    },

    // 5.查询集群磁盘总量
    getDisk() {
      let self = this;
      let path = this.$api.monitorApi.query1;
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      axios
        .get(path, {
          params: {
            query:
              "sum(node_filesystem_size_bytes{mountpoint='/',  fstype=~'ext4|xfs'})",
          },
        })
        .then((res) => {
          if (res.data.status) {
            let disk = res.data.data.result;
            for (let i = 0; i < disk.length; i++) {
              let diskValue = disk[i].value;
              //  let num = 1024.00
              self.allDisk = (
                diskValue[1] /
                self.num /
                self.num /
                self.num
              ).toFixed(2);
            }
            self.changeValue += 1;
          } else {
          }
        });
    },
    // 6.查询集群磁盘空闲量
    getDiskKong() {
      let self = this;
      let path = this.$api.monitorApi.query1;
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      axios
        .get(path, {
          params: {
            query:
              "sum(node_filesystem_free_bytes{mountpoint='/',  fstype=~'ext4|xfs'})",
          },
        })
        .then((res) => {
          if (res.data.status) {
            let freeValue = res.data.data.result;
            for (let i = 0; i < freeValue.length; i++) {
              let diskValue = freeValue[i].value;
              self.kongDisk = (
                diskValue[1] /
                self.num /
                self.num /
                self.num
              ).toFixed(2);
            }
            self.changeValue += 1;
          } else {
          }
        });
    },
    // 7.查询指定节点的负载
    getLoad() {
      let path = this.$api.monitorApi.query1;
      // let path = "http://piecloud.piesat.cn/prometheus/api/v1/query";
      axios
        .get(path, {
          params: {
            query: 'node_load1{instance="master"}',
          },
        })
        .then((res) => {
          if (res.data.status) {
            let nameData = res.data.data.result;
          } else {
          }
        });
    },
    //8.查询网络下载速度
    getDownLoad(first, second, third) {
      let self = this;
      let columm = this.$echarts.init(document.getElementById("lineChart2"));
      // let start = 1593669600;
      // let end = 1593676800;
      // let step = 36;
      let start = first;
      let end = second;
      let step = third;
      let url =
        this.$api.monitorApi.query_range +
        `sum(rate(node_network_receive_bytes_total[5m]))&start=${start}&end=${end}&step=${step}`;
      axios
        .get(url)
        .then((res) => {
          let resData = res.data.data.result[0].values;
          let tData = [];
          let vData = [];
          for (let i = 0; i < resData.length; i++) {
            // x轴时间处理
            let newDate = resData[i][0] * 1000;
            newDate = new Date(newDate);
            let newDateY = newDate.getFullYear();
            let newDateMon = newDate.getMonth() + 1;
            let newDateD = newDate.getDate();
            let newDateH = newDate.getHours();
            let newDateMin = newDate.getMinutes();
            let newDateS = newDate.getSeconds();
            // let wholeDate = newDateY +"-"+newDateMon+"-"+newDateD+" "+newDateH+":"+newDateMin+":"+newDateS ;
            let wholeDate = newDateH + ":" + newDateMin;
            // y轴值
            let newValue = resData[i][1];
            // Byte转M
            newValue = newValue / 1024.0 / 1024.0;
            newValue = newValue.toFixed(2);
            // push进新数组
            tData.push(wholeDate);
            vData.push(newValue);
          }
          self.optionsDownload.series[0].data = vData;
          self.optionsDownload.xAxis.data = tData;
          columm.setOption(this.optionsDownload);
        })
        .catch((err) => {
          cosnole.log(err);
        });
    },
    //9.查询网络上传速度
    getTransmit(first, second, third) {
      let self = this;
      let columm = this.$echarts.init(document.getElementById("lineChart3"));
      // let start = 1593669600;
      // let end = 1593676800;
      // let step = 36;
      let start = first;
      let end = second;
      let step = third;
      // let url = `http://piecloud.piesat.cn/prometheus/api/v1/query_range?query=sum(rate(node_network__transmit_bytes_total[5m]))&start=${start}&end=${end}&step=${step}`
      let url =
        this.$api.monitorApi.query_range +
        `sum(rate(node_network_transmit_bytes_total[5m]))&start=${start}&end=${end}&step=${step}`;
      axios
        .get(url)
        .then((res) => {
          let resData = res.data.data.result[0].values;
          let tData = [];
          let vData = [];
          for (let i = 0; i < resData.length; i++) {
            // x轴时间处理
            let newDate = resData[i][0] * 1000;
            newDate = new Date(newDate);
            let newDateY = newDate.getFullYear();
            let newDateMon = newDate.getMonth() + 1;
            let newDateD = newDate.getDate();
            let newDateH = newDate.getHours();
            let newDateMin = newDate.getMinutes();
            let newDateS = newDate.getSeconds();
            // let wholeDate = newDateY +"-"+newDateMon+"-"+newDateD+" "+newDateH+":"+newDateMin+":"+newDateS ;
            let wholeDate = newDateH + ":" + newDateMin;
            // y轴值
            let newValue = resData[i][1];
            // Byte转M
            newValue = newValue / 1024.0 / 1024.0;
            newValue = newValue.toFixed(2);
            // push进新数组
            tData.push(wholeDate);
            vData.push(newValue);
          }
          self.optionsUpload.series[0].data = vData;
          self.optionsUpload.xAxis.data = tData;
          columm.setOption(this.optionsUpload);
        })
        .catch((err) => {
          cosnole.log("getTransmitERROR", err);
        });
    },
  },
};
</script>



<!--<style>
.iframe {
  width: 100%;
  height: 770px;
  border: 1px saddlebrown;
}
.main {
  height: 100%;
}
@media (min-width: 1440px) {
  .echarts {
    display: inline-block;
    margin-left: 3%;
  }
}
@media screen and (min-width: 1367px) {
  .contentFirst,
  .contentThree {
    position: relative;
    top: -65px;
    font-size: 16px;
  }
  .lineChart {
    width: 92%;
    height: 400px;
    left:50px;
  }
  .titleText {
    font-size: 16px;
    font-weight: bold;
  }
  .contentFirst {
    left: 10%;
  }
  .imgSize {
    width: 100px;
    height: 100px;
  }
  .serverStyle {
    /* width:1260px; */
    width:72vw;
    display: flex;
    flex-wrap:wrap;
    margin-left: 9%;
    /* overflow:auto; */
  }
  .echarts {
    display: inline-block;
    margin-left: 8%;
  }
  .echartsImg {
    width: 300px;
    height: 300px;
  }
  .nodeNameContent {
    font-size: 18px;
    text-align: center;
  }
  .serverDiv {
    margin-left: 40px;
    cursor: pointer;
  }
  .dashboardContainer{
    margin-left:60px;
  }
}
@media screen and (max-width: 1366px) {
  .echarts {
    display: inline-block;
  }
  .firstecharts {
    margin-left: 11%;
  }
  .serverStyle {
    display: flex;
    margin-left: 9%;
    flex-wrap:wrap;
  }
  .lineChart {
    width: 100%;
    height: 400px;
  }
  .contentFirst {
    left: 13%;
  }
  .serverDiv {
    margin-right: 40px;
  }
  .contentFirst,
  .contentThree {
    position: relative;
    top: -65px;
    font-size: 16px;
  }
  .echartsImg {
    width: 300px;
    height: 300px;
  }
  .firstecharts {
    margin-left: 50px;
  }
  .lineChart {
    width: 100%;
    height: 400px;
  }
}
</style>-->



<style scoped>
/deep/.card {
  margin-bottom: 0;
}
/deep/.card-body {
  overflow-y: auto;
  padding: 15px;
}
.iframe {
  width: 100%;
  height: 770px;
  border: 1px saddlebrown;
}
.main {
  height: 100%;
}
.creation {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex-wrap: nowrap;
  padding-right: 15px;
}
.creation .title {
  font-size: 16px;
  font-weight: 700;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #cccccc;
}
.creation .content {
  font-size: 12px;
  height: 40px;
  line-height: 40px;
}

.serverDiv {
  cursor: pointer;
  margin-right: 15px;
}

@media (min-width: 1440px) {
  .echarts {
    display: inline-block;
  }
  .serverDiv {
    cursor: pointer;
    margin-right: 25px;
    align-items: flex-start;
  }
}
@media screen and (min-width: 1367px) {
  .titleText {
    font-size: 16px;
    font-weight: bold;
  }
  .imgSize {
    width: 100px;
    height: 100px;
  }

  .lineChart {
    height: calc(100% - 24px);
  }
  .serverDiv {
    cursor: pointer;
    margin-right: 25px;
    align-items: flex-start;
  }

  .serverStyle {
    /* width:1260px; */
    height: calc(100% - 34px);
    overflow: auto;
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    /* overflow:auto; */
  }
  .echarts {
    display: flex;
    justify-content: center;
    box-shadow: 0 0 5px #ccc;

    width: 33.3%;
  }
  .echartsImg {
    width: 200px;
    height: 200px;
  }
  .nodeNameContent {
    font-size: 18px;
    text-align: center;
  }

  .dashboardContainer {
    display: flex;
  }
}
@media screen and (max-width: 1366px) {
  .echarts {
    display: inline-block;
  }

  .serverDiv {
    cursor: pointer;
    margin-right: 25px;
    align-items: flex-start;
  }
  .serverStyle {
    display: flex;

    flex-wrap: wrap;
  }
  .lineChart {
    width: 100%;
  }
  .contentFirst {
    left: 13%;
  }
  .contentFirst,
  .contentThree {
    position: relative;
    top: -65px;
    font-size: 16px;
  }
  .echartsImg {
    width: 300px;
    height: 300px;
  }
  .firstecharts {
    margin-left: 50px;
  }
  .lineChart {
    width: 100%;
    height: 400px;
  }
}

.serverDiv {
  cursor: pointer;
  margin-right: 25px;
  align-items: flex-start;
}
</style>
